package com.example.baserecyclerviewadapterdemo.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.example.baserecyclerviewadapterdemo.R;
import com.example.baserecyclerviewadapterdemo.adapter.LoadMoreAdapter;
import com.example.baserecyclerviewadapterdemo.base.BaseActivity;
import com.example.baserecyclerviewadapterdemo.data.DataServer;
import com.example.baserecyclerviewadapterdemo.entity.Status;

import java.util.List;

public class LoadMoreRefreshActivity extends BaseActivity {
    class PageInfo{
        int page = 0;
        void nextPage(){
            page++;
        }
        void reset(){
            page = 0;
        }
        boolean isFirstPage(){
            return page == 0;
        }
    }
    private PageInfo pageInfo = new PageInfo();
    private static int PAGE_SIZE = 5;
    private SwitchCompat switchCompat;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout refreshLayout;
    private LoadMoreAdapter adapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_more);

        getParentToolbar().setTitle("加载更多测试");
        getParentToolbar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        switchCompat = findViewById(R.id.autoLoadMoreSwitch);
        recyclerView = findViewById(R.id.rv_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout = findViewById(R.id.swipeLayout);
        initAdapter();
        addHeadView();
        initRefreshLayout();
        initLoadMore();
        initSwitch();
    }

    private void initSwitch() {
        switchCompat.setChecked(adapter.getLoadMoreModule().isAutoLoadMore());
        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                adapter.getLoadMoreModule().setAutoLoadMore(isChecked);
                if (isChecked) {
                    switchCompat.setText("自动加载（开）");
                }else{
                    switchCompat.setText("自动加载（关）");
                }
            }
        });
    }

    private void initLoadMore() {
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        adapter.getLoadMoreModule().setAutoLoadMore(true);
        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void addHeadView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_head_view,(ViewGroup) recyclerView.getParent(),false);
        ((ImageView)headerView.findViewById(R.id.iv)).setImageResource(R.mipmap.ic_refresh);
        ((TextView)headerView.findViewById(R.id.tv)).setText("点击此处刷新");
        adapter.addHeaderView(headerView);

    }

    @Override
    protected void onStart() {
        super.onStart();
        refreshLayout.setRefreshing(true);
        refresh();
    }

    private void initAdapter(){
        adapter = new LoadMoreAdapter();
        adapter.setAnimationEnable(true);
        recyclerView.setAdapter(adapter);
        /*adapter.setList(DataServer.getSampleData(100));*/
    }
    private void initRefreshLayout(){
        refreshLayout.setColorSchemeColors(Color.rgb(47,223,189));
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    private void refresh() {
        adapter.getLoadMoreModule().setEnableLoadMore(false);
        pageInfo.reset();
        request();
    }
    private void loadMore(){
        request();
    }

    private void request() {
        new Request(pageInfo.page, new RequestCallback() {
            @Override
            public void success(List<Status> data) {
                refreshLayout.setRefreshing(false);
                adapter.getLoadMoreModule().setEnableLoadMore(true);
                if (pageInfo.isFirstPage()) {
                    adapter.setList(data);
                }else {
                    adapter.addData(data);
                }
                if (data.size() < PAGE_SIZE) {
                    adapter.getLoadMoreModule().loadMoreEnd();
                }else{
                    adapter.getLoadMoreModule().loadMoreComplete();
                }
                pageInfo.nextPage();
            }

            @Override
            public void fail(Exception e) {
                refreshLayout.setRefreshing(false);
                adapter.getLoadMoreModule().setEnableLoadMore(true);
                adapter.getLoadMoreModule().loadMoreFail();
            }
        }).start();
    }

    static class Request extends Thread{
        private int mPage;
        private RequestCallback mCallback;
        private Handler handler;

        private static boolean mFirstPageNoMore;
        private static boolean mFirstError = true;

        public Request(int page,RequestCallback callback){
            this.mPage = page;
            this.mCallback = callback;
            handler = new Handler(Looper.getMainLooper());
        }
        @Override
        public void run() {
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (mPage == 10 && mFirstError) {
                mFirstError = false;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mCallback.fail(new RuntimeException("fail"));
                    }
                });
            }else{
                int size = PAGE_SIZE;
                if (mPage == 1) {
                    if (mFirstPageNoMore) {
                        size = 1;
                    }
                    mFirstPageNoMore = !mFirstPageNoMore;
                    if (!mFirstError) {
                        mFirstError = true;
                    }
                }else if(mPage == 4){
                    size = 1;
                }
                final int dataSize = size;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mCallback.success(DataServer.getSampleData(dataSize));
                    }
                });
            }
        }
    }
    interface RequestCallback{
        void success(List<Status> data);

        void fail(Exception e);
    }
}
